
package com.zhu.salesmanagement;

import java.util.ArrayList;
import java.util.List;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.MKOLUpdateElement;
import com.baidu.mapapi.MKOfflineMap;
import com.baidu.mapapi.MKOfflineMapListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.network.PutCustomerData;
import com.zhu.salesmanagement.network.SyncNearCustomerData;
import com.zhu.salesmanagement.overlays.StadiumOverlay;
import com.zhu.salesmanagement.overlays.StadiumOverlayItem;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.ObservableScrollView;

import android.app.Activity;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * 地图拜访
 */
public class MapVisitedListActivity extends MapActivity implements View.OnClickListener, StadiumOverlay.OnTapClickListener {

    private final static String TAG = "MapVisitedListActivity";

    public final static int MAP_ZOOM_LEVEL = 15 ;
    public final static double DEFAULT_LAT = 31.2367;
    public final static double DEFAULT_LNG = 121.50107;

    private final static int CPOS_LIST_QUERY_TOKEN = 1002;
    private final static int CVISITED_LIST_QUERY_TOKEN = 1003;
    private final static int PC_LIST_QUERY_TOKEN = 1004;
    private final static int TASK_LIST_DELETE_TOKEN = 2000;

    private static final int UPDATE_DB = 1000;

    private boolean isChange = false;
    private ArrayList<VisitTaskInfo> mVisitTaskList = null;
    private View mCheckView = null;
    private Spinner mSpinner = null;
    private FrameLayout mFrameLayout = null;
    private MyLocation mMyLocation = null;
    private Location mCurLocation = null;
    private VisitTaskInfo mCheckingVisitTaskInfo = null;
    private int mCurCheckType = -1;
    private boolean isChecking = false;
    private AnimationDrawable mAnimation = null;
    private boolean isFirstLoding = true;
    private DataQueryHandler mDataQueryHandler = null;
    private int mDistanceIndex = 0;
    private String[] mDistanceValue = null;
    private BMapManager mapManager;
    private MapView mapView;
    private MKOfflineMap mOffline = null;
    private MapController mapController;
    private SyncNearCustomerData mSyncNearCustomerData = null;
    private PutCustomerData mSyncCustomerData = null;
    private Button mVisitConnect = null;
    String mStoreWhere = "";
    public static String[] PROJECTION = new String[]{ SalesSettings.ProductShelfsColumns.CUSTOMER_ID };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.mapvisitedlist_main);

        mapManager = SalesApplication.mApplicaton.getMapManager();
        if (mapManager == null) {
            Log.e("zhu","mapManager is null");
            mapManager = new BMapManager(getApplication());
            mapManager.init(SalesApplication.mStrKey, new SalesApplication.MyGeneralListener());
        }

        mVisitTaskList = new ArrayList<VisitTaskInfo>();
        mDataQueryHandler = new DataQueryHandler(this.getContentResolver());
        mDistanceValue = this.getResources().getStringArray(R.array.distance_value);

        super.initMapActivity(mapManager);

        setupViews();
        initMapView();
        initSpinner();
    }

    public void onResume() {
        super.onResume();
        if (mapManager != null) {
            mapManager.start();
        }
        Actions.setAutoTime(this);
    }

    /**
     * 初始化界面
     */
    private void setupViews() {
        mFrameLayout = (FrameLayout) findViewById(R.id.nearstorelistLayout);
        mSpinner = (Spinner) findViewById(R.id.nearstore_jiti);
        mVisitConnect = (Button)findViewById(R.id.visit_connect);
        mVisitConnect.setOnClickListener(this);
        findViewById(R.id.visit_back).setOnClickListener(this);
    }

    /**
     * 初始化地图界面
     */
    private void initMapView(){
        mapView = (MapView) findViewById(R.id.map_view);
        mapView.setTraffic(false);
        mapView.setSatellite(false);
        mapView.setBuiltInZoomControls(true);
        mapView.setDrawOverlayWhenZooming(true);
        GeoPoint point = new GeoPoint((int) (DEFAULT_LAT * 1E6), (int) (DEFAULT_LNG * 1E6));
        mapController = mapView.getController();
        mapController.setCenter(point);
        mapController.setZoom(MAP_ZOOM_LEVEL);

        mOffline = new MKOfflineMap();
        mOffline.init(mapManager, new MKOfflineMapListener() {
            @Override
            public void onGetOfflineMapState(int type, int state) {
                switch (type) {
                    case MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
                    {
                    MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                    // mText.setText(String.format("%s : %d%%", update.cityName,
                    // update.ratio));
                    }
                    break;
                case MKOfflineMap.TYPE_NEW_OFFLINE:
                    Log.d("zhu", String.format("add offlinemap num:%d", state));
                    break;
                case MKOfflineMap.TYPE_VER_UPDATE:
                    Log.d("zhu", String.format("new offlinemap ver"));
                    break;
            }
        }
        });
        int num = mOffline.scan();
        if(Actions.DEBUG){
            Log.e("zhu","num="+num);
        }
    }

    /**
     * 初始化距离
     */
    private void initSpinner() {
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(
                        R.array.distance_type));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                TextView tv = (TextView) arg1;
                tv.setTextColor(getResources().getColor(R.color.white));
                mDistanceIndex = arg2;
                if(Actions.DEBUG){
                    Log.e("zhu", "initSpinner");
                }
                isFirstLoding = true;
                if (mMyLocation == null) {
                    mMyLocation = new MyLocation(MapVisitedListActivity.this, true, false);
                }
                mMyLocation.getLocation(locationResult, false);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
        mSpinner.setSelection(2);
    }

    /**
     * 更新拜访点界面
     */
    private void updateView() {
        if(Actions.DEBUG){
            Log.e("zhu","size="+mVisitTaskList.size());
        }
        if(mVisitTaskList.size() == 0){
            this.mapView.getOverlays().clear();
            Actions.toastShort(this, this.getString(R.string.mapnocustomer));
        }else{
            addOverlays();
        }
        mapView.invalidate();
    }

    /**
     * 点击事件处理
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.checkpop_editcrc:
                    gotoProductInfoActivity(mCheckingVisitTaskInfo);
                    break;
                case R.id.visit_back:
                case R.id.visittask_back:
                    if (isChange) {
                        setResult(RESULT_OK);
                    }
                    finish();
                    break;
                case R.id.checkpop_close:
                    if (mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1) {
                        mFrameLayout.removeView(mCheckView);
                    }
                    break;
                case R.id.popcheck_blank:
                    break;
                case R.id.checkpop_storepop:
                    gotoStoreInfoActivity((VisitTaskInfo) v.getTag());
                    break;
                case R.id.checkpop_put:
                	if(mSyncCustomerData == null){
                        mSyncCustomerData = new PutCustomerData(this, this.getLayoutInflater(), mHandler, mFrameLayout);
                    }
                    VisitTaskInfo item = (VisitTaskInfo) v.getTag();
                    if(mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1){
                        mFrameLayout.removeView(mCheckView);
                    }
                    mSyncCustomerData.statSync(item.id, item.mName);
                	break;
                case R.id.visit_connect:
                	//startRequestNearData();
                	if (mMyLocation == null) {
                        mMyLocation = new MyLocation(MapVisitedListActivity.this, true, false);
                    }
                    mMyLocation.getLocation(locationResult, false);
                	break;
                case R.id.checkpop_download:
                	startRequestCustomerData((VisitTaskInfo) v.getTag());
                	break;
            }
        }
    }

    /**
     * 跳转门店属性界面
     * @param info 门店信息
     */
    private void gotoStoreInfoActivity(VisitTaskInfo info) {
        Intent intent = new Intent(MapVisitedListActivity.this, StoreInfoActivity.class);
        intent.putExtra(StoreInfoActivity.STR_TYPE, StoreInfoActivity.TYPE_FROMVISIT);
        intent.putExtra(StoreInfoActivity.STR_STOREID, info.id);
        startActivity(intent);
    }

    /**
     * 跳转门店信息录入界面
     * @param info 门店信息
     */
    private void gotoProductInfoActivity(VisitTaskInfo info) {
    	if (mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1) {
            mFrameLayout.removeView(mCheckView);
        }
        Intent intent = null;
        if (info.type == VisitTaskInfo.STORE_DEALER) {
            intent = new Intent(MapVisitedListActivity.this, DealerTaskListActivity.class);
        } else {
            intent = new Intent(MapVisitedListActivity.this, StoreEvaluationActivity.class);
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", info);
        intent.putExtras(bundle);
        startActivityForResult(intent, UPDATE_DB);
    }

    /**
     * 弹出门店事件选择框
     * @param visitTaskInfo 门店信息
     */
    private void popCheckView(VisitTaskInfo visitTaskInfo) {
        if (mCheckView == null) {
            mCheckView = getLayoutInflater().inflate(R.layout.layout_popcheck_map, null);
            mCheckView.setOnClickListener(this);
            ImageView close = (ImageView) mCheckView.findViewById(R.id.checkpop_close);
            close.setOnClickListener(this);
        }
        TextView name = (TextView) mCheckView.findViewById(R.id.checkpop_title);
        name.setText(visitTaskInfo.mName);
        Button crc = (Button) mCheckView.findViewById(R.id.checkpop_editcrc);
        Button property = (Button) mCheckView.findViewById(R.id.checkpop_storepop);
        Button put = (Button) mCheckView.findViewById(R.id.checkpop_put);
        Button download = (Button) mCheckView.findViewById(R.id.checkpop_download);
        property.setTag(visitTaskInfo);
        crc.setTag(visitTaskInfo);
        put.setTag(visitTaskInfo);
        download.setTag(visitTaskInfo);

        if(visitTaskInfo.needDownload){
        	setButtonEnable(crc, false, R.drawable.crc_gray);
        	setButtonEnable(download, true, R.drawable.icon_xiazai_foucus);
        }else{
            if(visitTaskInfo.isPutSuccess){
                setButtonEnable(crc, false, R.drawable.crc_gray);
            }else{
                setButtonEnable(crc, true, R.drawable.crc);
            }
            setButtonEnable(download, false, R.drawable.icon_xiazai);
        }

        if(visitTaskInfo.iProperty == 0){
            setButtonEnable(property, false, R.drawable.property);
        }else{
            setButtonEnable(property, true, R.drawable.property_blue);
        }
        if(visitTaskInfo.canPut){
            setButtonEnable(put, true, R.drawable.icon_shangchuan);
        }else{
            setButtonEnable(put, false, R.drawable.icon_shangchuan_normal);
        }
        mCheckingVisitTaskInfo = visitTaskInfo;
        mFrameLayout.addView(mCheckView);
    }

    /**
     * 设置按钮状态
     * @param button 按钮
     * @param isEnabled 开启
     * @param resId 图片资源ID
     */
    private void setButtonEnable(Button button, boolean isEnabled, int resId){
        if(isEnabled){
            button.setEnabled(true);
            button.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(resId), null, null);
            button.setTextColor(getResources().getColor(R.color.visit_blue));
            button.setOnClickListener(this);
        }else{
            button.setEnabled(false);
            button.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(resId), null, null);
            button.setTextColor(getResources().getColor(R.color.visit_gray));
            button.setOnClickListener(null);
        }
    }

    public void onDestroy() {
        if (mMyLocation != null) {
            mMyLocation.destroy();
        }
        super.onDestroy();
    }

    /**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!doBack()) {
                finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 返回事件处理
     */
    private boolean doBack() {
        if (mFrameLayout.indexOfChild(mCheckView) != -1) {
            mFrameLayout.removeView(mCheckView);
            return true;
        }
        if(mSyncNearCustomerData != null && mSyncNearCustomerData.isSync()){
            return true;
        }
        if(mSyncCustomerData != null && mSyncCustomerData.isSync()){
            return true;
        }
        return false;
    }

    /**
     * 按键事件拦截
     */
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (isChecking) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 触摸事件拦截
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (isChecking) {
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 签入签出
     * @param type 类型 签入OR签出
     */
    private void startCheck(int type) {
        isChange = true;
        mCurLocation = null;
        isChecking = true;
        mCurCheckType = type;
        mCheckView.findViewById(R.id.checkpop_botton).setVisibility(View.INVISIBLE);
        mCheckView.findViewById(R.id.checkpop_close).setVisibility(View.INVISIBLE);
        mCheckView.findViewById(R.id.checkpop_animation).setVisibility(View.VISIBLE);
        TextView text = (TextView) mCheckView.findViewById(R.id.checkpop_animationText);
        if (mCurCheckType == VisitTaskListActivity.CHECK_IN) {
            text.setText(R.string.checkining);
        } else {
            text.setText(R.string.checkouting);
        }
        ImageView view = (ImageView) mCheckView.findViewById(R.id.checkpop_animationImage);
        mAnimation = (AnimationDrawable) view.getBackground();
        mAnimation.setLevel(0);
        mAnimation.start();
        if (mMyLocation == null) {
            mMyLocation = new MyLocation(this, false, false);
        }
        mMyLocation.getLocation(locationResult, true);
    }

    /**
     * 签出OR签入结束
     */
    private void stopCheck() {
        boolean success = saveData();
//        if (mCurCheckType == VisitTaskListActivity.CHECK_IN) {
//            mCheckingButtom.setImageResource(R.drawable.pop_checkout);
//        } else {
//            mCheckingButtom.setImageResource(R.drawable.pop_check_disable);
//            mCheckingButtom.setEnabled(false);
//        }
        isChecking = false;
        mAnimation.stop();
        mFrameLayout.removeView(mCheckView);
        if (mCheckingVisitTaskInfo.isVisited) {
            // updateCheckView(mCheckingVisitTaskInfo);
        }
        mCheckingVisitTaskInfo = null;
        //mCheckingButtom = null;
        mCheckView.findViewById(R.id.checkpop_botton).setVisibility(View.VISIBLE);
        mCheckView.findViewById(R.id.checkpop_close).setVisibility(View.VISIBLE);
        mCheckView.findViewById(R.id.checkpop_animation).setVisibility(View.GONE);
    }

    /**
     * 定位结果
     */
    public LocationResult locationResult = new LocationResult() {

        public void gotLocation(final Location location) {
            // Got the location!
            if (location != null) {
            	//location.setLatitude(31.233298);
            	//location.setLongitude(121.419614);
                mCurLocation = location;
            }
            if (isFirstLoding) {
                isFirstLoding = false;
                getData();
            } else {
            	startRequestNearData();
            }
            if(location != null){
                GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6));
                mapController.setCenter(pt);
            }
        }
    };

    /**
     * 保存签入OR签出数据
     */
    private boolean saveData() {
        double lat = 0;
        double lng = 0;
        if (mCurLocation != null) {
            lat = mCurLocation.getLatitude();
            lng = mCurLocation.getLongitude();
        }
        if(lat == 0 && lng == 0){
            Location location = Util.mGetGpsLocation.getLastLocation();
            if(location != null){
                lat = location.getLatitude();
                lng = location.getLongitude();
            }
        }
        if (mCurCheckType == VisitTaskListActivity.CHECK_IN) {
            mCheckingVisitTaskInfo.mCheckinTime = String.valueOf(mMyLocation.getCurrentTime()/*System.currentTimeMillis()*/);
            boolean success = Util.saveStoresCheckinInfo(this, mCheckingVisitTaskInfo, lat, lng,
                    true);
            if (success) {
                if (lat == 0 && lng == 0) {
                    Actions.toastShort(this, getString(R.string.checkinsuccess_fail));
                } else {
                    Actions.toastShort(this, getString(R.string.checkin_success));
                }
                return true;
            } else {
                mCheckingVisitTaskInfo.mCheckinTime = "";
                return false;
            }
        } else {
            mCheckingVisitTaskInfo.mCheckoutTime = String.valueOf(mMyLocation.getCurrentTime()/*System.currentTimeMillis()*/);
            boolean success = Util.saveStoresCheckoutInfo(this, mCheckingVisitTaskInfo, lat, lng);
            if (success) {
                if (lat == 0 && lng == 0) {
                    Actions.toastShort(this, getString(R.string.checkoutsuccess_fail));
                } else {
                    Actions.toastShort(this, getString(R.string.checkout_success));
                }
                mCheckingVisitTaskInfo.isVisited = true;
                return true;
            } else {
                mCheckingVisitTaskInfo.mCheckoutTime = "";
                return false;
            }
        }
    }

    /**
     * 获取门店数据
     */
    private void getData() {
        if (mCurLocation == null) {
            Actions.toastShort(this, this.getString(R.string.getlocationerror));
        } else {
            startTaskListAsyncQuery();
        }
        mMyLocation.destroy();
        mMyLocation = null;
    }

    /**
     * 开始获取门店数据
     */
    private void startTaskListAsyncQuery() {
        try {
            mDataQueryHandler.startQuery(CPOS_LIST_QUERY_TOKEN, null,
                    SalesSettings.CustomerSColumns.CONTENT_URI,
                    null, null, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新门店数据
     * @param cursor 数据库数据
     */
    private void updateCustomerPosList(Cursor cursor) {
        if (mVisitTaskList != null) {
            mVisitTaskList.clear();
        }
        mStoreWhere = "";
        try {
            final int storeidIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ID);
            final int latIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LAT);
            final int lngIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LNG);
            final int nameIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_NAME);
            final int typeIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE);
            final int addrIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS);
            final int propertyIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY);
            final int areaidIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_AREAID);
            final int crctimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_CRCNEARTIME);
            final int sctimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_SCNEARTIME);
            final int dealernameIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_DEALERNAME);
            final int scategortIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_SCATEGORT);
            final int msgIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.IMPORTANTINFO);

            while (cursor.moveToNext()) {
                String cid = cursor.getString(storeidIndex);
                Double lat = Double.parseDouble(cursor.getString(latIndex));
                Double lng = Double.parseDouble(cursor.getString(lngIndex));

                VisitTaskInfo visitTaskInfo = new VisitTaskInfo();
                visitTaskInfo.id = cid;
                visitTaskInfo.mName = cursor.getString(nameIndex);
                visitTaskInfo.type = Integer.parseInt(cursor.getString(typeIndex));
                visitTaskInfo.mAddress = cursor.getString(addrIndex);
                if(Actions.DEBUG){
                    Log.e("zhu", cursor.getString(typeIndex));
                }
                visitTaskInfo.mLatitude = Double.parseDouble(cursor.getString(latIndex));
                visitTaskInfo.mLongitude = Double.parseDouble(cursor.getString(lngIndex));
                visitTaskInfo.iProperty = cursor.getInt(propertyIndex);
                visitTaskInfo.sAreaID = cursor.getString(areaidIndex);
                visitTaskInfo.sDealtSalesPerson = cursor.getString(dealernameIndex);
                visitTaskInfo.sCRCNearTime = cursor.getString(crctimeIndex);
                visitTaskInfo.sSCNearTime = cursor.getString(sctimeIndex);
                visitTaskInfo.sStoreCategory = cursor.getString(scategortIndex);
                visitTaskInfo.sMsg = cursor.getString(msgIndex);
                if (isNear(lat, lng)) {
                    mVisitTaskList.add(visitTaskInfo);
                    if (mStoreWhere.length() == 0) {
                    	mStoreWhere = SalesSettings.VisitedStoresColumns.STOREID + " = \"" + visitTaskInfo.id + "\"";
                    } else {
                    	mStoreWhere += " OR "+ SalesSettings.VisitedStoresColumns.STOREID +" = \"" + visitTaskInfo.id + "\"";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
            cursor.close();
        }

        if(mVisitTaskList.size() == 0){
        	Actions.toastShort(this, getString(R.string.zaixianclew));
            return;
        }

        try {
            if (mStoreWhere.length() > 1) {
                mDataQueryHandler.startQuery(CVISITED_LIST_QUERY_TOKEN, null,
                        SalesSettings.VisitedStoresColumns.CONTENT_URI,
                        null, mStoreWhere, null, null);
            } else {
                updateView();
            }
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新门店拜访信息数据
     * @param cursor 数据库数据
     */
    private void updateVisitedList(Cursor cursor) {
        try {
            final int idIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
            final int storeidIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            final int itemnoIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.ITEMNO);
            final int checkintimeIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            final int pustatusIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.PUTSTATUS);
            final int putsuccessIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.PUTSUCCESS);
            final int checkresultIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKRESULT);
            final int checkinfoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKRINFO);
            final int dtidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.DTASKACTUALID);

            while (cursor.moveToNext()) {
                String cid = cursor.getString(storeidIndex);
                VisitTaskInfo visitTaskInfo = getVisitTaskInfo(cid);
                visitTaskInfo.mDbId = cursor.getLong(idIndex);
                visitTaskInfo.id = cursor.getString(storeidIndex);
                visitTaskInfo.itemId = cursor.getInt(itemnoIndex);
                visitTaskInfo.mCheckinTime = cursor.getString(checkintimeIndex);
                visitTaskInfo.canPut = cursor.getInt(pustatusIndex) == 1 ? true : false;
                visitTaskInfo.isPutSuccess = cursor.getInt(putsuccessIndex) == 1 ? true : false;
                visitTaskInfo.sCheckResult = cursor.getString(checkresultIndex);
            	visitTaskInfo.sCheckInfo = cursor.getString(checkinfoIndex);
            	visitTaskInfo.mDatingTaskActualID = cursor.getString(dtidIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
            cursor.close();
        }

        mDataQueryHandler.startQuery(PC_LIST_QUERY_TOKEN, null,
                SalesSettings.ProductShelfsColumns.CONTENT_URI,
                PROJECTION, mStoreWhere, null, null);
        //updateView();
    }

    /**
     * 根据门店货架信息更新是否需要下载客户数据
     * @param cursor 数据库数据
     */
    private void updatePCShelfsList(Cursor cursor) {
        try {
            final int storeidIndex = cursor
                    .getColumnIndexOrThrow(SalesSettings.ProductShelfsColumns.CUSTOMER_ID);

            while (cursor.moveToNext()) {
                String cid = cursor.getString(storeidIndex);
                VisitTaskInfo visitTaskInfo = getVisitTaskInfo(cid);
                visitTaskInfo.needDownload = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        	}
        }
        updateView();
    }

    /**
     * 根据ID获取拜访门店信息
     * @param sid 门店id
     */
    private VisitTaskInfo getVisitTaskInfo(String sid) {
        for (int i = 0; i < mVisitTaskList.size(); i++) {
            VisitTaskInfo visitTaskInfo = mVisitTaskList.get(i);
            if (visitTaskInfo.id.equals(sid)) {
                return visitTaskInfo;
            }
        }
        return null;
    }

    private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case CPOS_LIST_QUERY_TOKEN:
                    updateCustomerPosList(cursor);
                    break;
                case CVISITED_LIST_QUERY_TOKEN:
                    updateVisitedList(cursor);
                    break;
                case PC_LIST_QUERY_TOKEN:
                	updatePCShelfsList(cursor);
                	break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case TASK_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    /**
     * 门店是否在选择返回内
     * @param lat
     * @param lng
     */
    private boolean isNear(double lat, double lng) {
        float neardistance = Float.parseFloat(mDistanceValue[mDistanceIndex]);
        boolean isNear = false;
        Location temLocation = new Location("PA");
        temLocation.setLatitude(lat);
        temLocation.setLongitude(lng);
        float distance = mCurLocation.distanceTo(temLocation);
        if (Actions.DEBUG) {
            Log.e("zhu", "distance=" + distance);
        }
        if (distance <= neardistance) {
            isNear = true;
        }
        return isNear;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case UPDATE_DB:
                isChange = true;
                startTaskListAsyncQuery();
                break;
        }
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected void onPause() {
        if (mapManager != null) {
            mapManager.stop();
        }
        super.onPause();
    }

    /**
     * 添加地图显示点
     */
    private void addOverlays() {
        List<Overlay> overlays = this.mapView.getOverlays();
        Drawable stadiumDrawable = getResources().getDrawable(R.drawable.db_r);
        StadiumOverlay stadiumOverlay = new StadiumOverlay(stadiumDrawable,
                this, null, this);

        for(int i = 0; i < mVisitTaskList.size(); i++){
            StadiumOverlayItem item = new StadiumOverlayItem(mVisitTaskList.get(i));
            stadiumOverlay.addOverlay(item);
        }

        //stadiumOverlay.setOnFocusChangeListener(onPopChangeListener);
        overlays.clear();
        overlays.add(stadiumOverlay);
    }

    private final ItemizedOverlay.OnFocusChangeListener onPopChangeListener = new ItemizedOverlay.OnFocusChangeListener() {
        public void onFocusChanged(ItemizedOverlay overlay, OverlayItem newFocus) {
            if (newFocus != null) {
                MapVisitedListActivity.this.mapController.animateTo(newFocus.getPoint());
                popCheckView(((StadiumOverlayItem)newFocus).getData());
            }
        }
    };

    @Override
    public void tapPoint(StadiumOverlayItem item) {
        // TODO Auto-generated method stub
        MapVisitedListActivity.this.mapController.animateTo(item.getPoint());
        popCheckView(item.getData());
    }

    /**
     * 在线请求附件门店数据
     */
    private void startRequestNearData(){
        if(mSyncNearCustomerData == null){
            mSyncNearCustomerData = new SyncNearCustomerData(this, this.getLayoutInflater(), mHandler, mFrameLayout);
        }
        mSyncNearCustomerData.statSync(mCurLocation);
    }

    /**
     * 在线请门店综合数据
     */
    private void startRequestCustomerData(VisitTaskInfo item){
    	if (mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1) {
            mFrameLayout.removeView(mCheckView);
        }
        if(mSyncNearCustomerData == null){
            mSyncNearCustomerData = new SyncNearCustomerData(this, this.getLayoutInflater(), mHandler, mFrameLayout);
        }
        mSyncNearCustomerData.statSync(mCheckingVisitTaskInfo);
    }

    /**
     * 在线请求返回结果处理
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SyncNearCustomerData.SYNC_SUCCESSEND:
                    startTaskListAsyncQuery();
                    mSyncNearCustomerData.remoView();
                    break;
                case SyncNearCustomerData.SYNC_FAILEDEND:
                    mSyncNearCustomerData.remoView();
                    Actions.toastShort(MapVisitedListActivity.this, MapVisitedListActivity.this.getString(R.string.getneardatafail));
                    break;
                case PutCustomerData.SYNC_SUCCESSEND:
                	startTaskListAsyncQuery();
                	mSyncCustomerData.remoView();
                	Actions.toastShort(MapVisitedListActivity.this, MapVisitedListActivity.this.getString(R.string.putdatasuccess));
                	break;
                case PutCustomerData.SYNC_FAILEDEND:
					mSyncCustomerData.remoView();
					Actions.toastShort(MapVisitedListActivity.this, MapVisitedListActivity.this.getString(R.string.putdatafail));
					break;
                case SyncNearCustomerData.SYNC_SUCCESSEND_CUSTOMER:
                	mSyncNearCustomerData.remoView();
                	mCheckingVisitTaskInfo.needDownload = false;
                	//startTaskListAsyncQuery();
                	gotoProductInfoActivity(mCheckingVisitTaskInfo);
                	break;
                case SyncNearCustomerData.SYNC_FAILEDEND_CUSTOMER:
                	mSyncNearCustomerData.remoView();
					Actions.toastShort(MapVisitedListActivity.this, MapVisitedListActivity.this.getString(R.string.getcustomerdatafail));
                	break;
            }
        }
    };
}
